package com.basic.hellorabbit.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

/**
* @Description:    文件上传
* @Author:         Joe
* @CreateDate:     2020/3/14 16:47
*/
@Controller
public class UploadController {

    /**
     * 跳转到单文件上传测试页面
     * @return
     */
    @RequestMapping(value = "/indexs",method = RequestMethod.GET)
    public String toUpload(){
        return "upload";
    }

    /**
     * 单文件上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(MultipartFile file, HttpServletRequest request){ //file必须与表单中name的值一致
        try {
            //1.创建文件在服务器端路径
            String dir = request.getServletContext().getRealPath("/upload");
            File file1 = new File(dir);
            if (!file1.exists()){ //如果文件路径不存在
                file1.mkdirs();   //就创建文件夹
            }
            //2.给文件生成一个新的存放名，防止重名
            //2.1 截取上传文件的后缀(扩展名)
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //2.2 新名字采用UUID+原始扩展名
            String fileName = UUID.randomUUID().toString()+fileSuffix;
            //3.文件新路径+文件全名
            File file2 = new File(file1+"/"+fileName);
            //4.开始上传
            file.transferTo(file2);

        }catch (Exception e){
            e.printStackTrace();
            return "文件上传失败";
        }
        return "文件上传成功";

    }

    /**
     * 跳转到批量上传测试页面
     * @return
     */
    @RequestMapping(value = "/index2",method = RequestMethod.GET)
    public String toUpload2(){
        return "upload2";
    }

    /**
     * 文件批量上传
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload2",method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile2(MultipartFile[] file, HttpServletRequest request){ //file必须与表单中name的值一致
        try {
            String dir = request.getServletContext().getRealPath("/upload");
            File file1 = new File(dir);
            if (!file1.exists()){
                file1.mkdirs();  
            }
            for (int i = 0; i < file.length; i++) {
                String fileSuffix = file[i].getOriginalFilename().substring(file[i].getOriginalFilename().lastIndexOf("."));
                String fileName = UUID.randomUUID().toString()+fileSuffix;
                File file2 = new File(file1+"/"+fileName);
                file[i].transferTo(file2);
            }
        }catch (Exception e){
            e.printStackTrace();
            return "文件批量上传失败";
        }
        return "文件批量上传成功";
    }
}
